<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <TreeTools :node-data="titleData" @toggle-box="toggleBox" />
        <el-tree :data="departs" :props="defaultProps">
          <template #default="{data}">
            <TreeTools :node-data="data" @on-success="onSuccess" @toggle-box="toggleBox" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <AddDept :operate-type="operateType" :dlist="dlist" :is-show-dept.sync="isShowDept" :current-pid="currentPid" @on-success="onSuccess" />
  </div>
</template>

<script>
import { reqGetDepartments } from '@/api/departments'
import TreeTools from './components/TreeTools.vue'
import AddDept from './components/AddDept.vue'
export default {
  name: 'Departments',
  components: {
    TreeTools,
    AddDept
  },
  data () {
    return {
      // 标志位 loading
      loding: false,
      // 标志位 操作类型
      operateType: 'add',
      // 原始的部门列表数据(用于表单验证)
      dlist: [],
      // 当前父级部门
      currentPid: '',
      // 控制添加部门弹窗标志位
      isShowDept: false,
      // 顶部标题数据
      titleData: {
        id: '',
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人',
        root: true
      },
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created () {
    // 初始化数据
    this.loadDepartments()
  },
  methods: {
    // 显示弹窗
    toggleBox (info) {
      this.isShowDept = info.isShow
      this.currentPid = info.id
      this.operateType = info.type
    },
    // 发请求
    async loadDepartments () {
      this.loading = true
      try {
        const { code, data } = await reqGetDepartments()
        if (code === 10000) {
          // 后端返回的原始数据列表
          this.dlist = data.depts
          this.titleData.name = data.companyName
          // 将请求数据添加到data数据，在此之前需要将数据转换为树状结构
          this.departs = this.translateListToTreeData(data.depts, '')
        }
      } catch { this.$message.warning('未能获得响应数据') } finally {
        this.loading = false
      }
    },
    // 封装函数-->普通数据结构转换为树状结构
    translateListToTreeData (list, pid) {
      const result = []
      list.forEach((item) => {
        if (item.pid === pid) {
          // 这里要递归了!!!
          const children = this.translateListToTreeData(list, item.id)
          item.children = children
          result.push(item)
        }
      })
      return result
    },
    // 删除成功后的初始化
    onSuccess () {
      this.loadDepartments()
    }
  }

}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 30px;
  font-size: 14px;
}
</style>
